import { SearchBar, Cascader, Image, Tag, Button, Popup, Toast, Collapse, Space } from 'antd-mobile'
import { useEffect, useState, useRef, useMemo } from 'react'
import { transformOptions, getSelected } from '@utils/index'
import { useNavigate } from 'react-router-dom'
import { FilterOutline } from 'antd-mobile-icons'
import { merchantExport, searchList, exportWord } from '@api'
import useFileDownloader from '@hooks/useFileDownloader'
import './index.scss'

const typeModalStyle = { height: '70vh', padding: '20px', boxSizing: 'border-box', borderRadius: '0 0 15px 15px' }
const Shop = () => {
    const navigate = useNavigate()

    const fileInputRef = useRef(null)

    const { downloadFile, loading, error } = useFileDownloader()

    const [visible1, setVisible1] = useState(false)

    // 筛选开关
    const [filterVisible, setFilterVisible] = useState(false)

    // 筛选数据
    const [selections, setSelections] = useState({})

    // 时间范围
    const [timeRange, setTimeRange] = useState({
        startDate: '',
        endDate: ''
    })

    // 地址
    const [addr, setAddr] = useState([])

    // 筛选数据
    const [categories, setCategories] = useState([])

    // 地址列表
    const [addrData, setAddrData] = useState([])

    // 列表数据
    const [merchant, setMerchant] = useState({})

    // 关键词
    const [keyword, setKeyword] = useState('')

    useEffect(() => {
        searchList().then(({ success, data }) => {
            if (success) {
                let arr = []
                let addrArr = []
                data.forEach((item) => {
                    if (item.title === '地址') {
                        addrArr = [...item.options]
                    }
                    if (item.title === '行业类型' || item.title === '检查状态') {
                        arr.push(item)
                    }
                })
                setCategories(arr)
                setAddrData(transformOptions(addrArr))
            }
        })
        getData()
    }, [])

    const merchantNum = useMemo(() => merchant?.total ?? 0, [merchant])

    const recordNum = useMemo(() => {
        return merchant?.records?.reduce((acc, item) => acc + (item.verifyList?.length || 0), 0) || 0
    }, [merchant])

    const handleSelect = (categoryID, optionID) => {
        if (categoryID === '检查状态') {
            setSelections((prev) => ({
                ...prev,
                [categoryID]: {
                    [optionID]: true
                }
            }))
        } else {
            setSelections((prev) => ({
                ...prev,
                [categoryID]: {
                    ...prev[categoryID],
                    [optionID]: !(prev[categoryID] && prev[categoryID][optionID])
                }
            }))
        }
    }

    // 获取数据
    const getData = () => {
        let a = getSelected(selections)
        let params = {
            keyword,
            current: 1,
            size: 10,
            province: addr[0],
            city: addr[1],
            area: addr[2],
            street: addr[3],
            village: addr[4],
            checkTimeStart: timeRange.startDate ? `${timeRange.startDate} 00:00:00` : '',
            checkTimeEnd: timeRange.endDate ? `${timeRange.endDate} 23:59:59` : '',
            statusName: a['检查状态']?.join(),
            trade: a['行业类型']
        }
        merchantExport(params).then(({ success, data, info }) => {
            if (success) {
                setMerchant(data)
            } else {
                Toast.show({ content: info })
                setMerchant([])
            }
        })
    }

    // 关闭类型弹窗
    const closeTypeModal = () => {
        console.log(selections, addr, timeRange)
        getData()
        setFilterVisible(false)
    }

    // 处理日期变更的函数
    const handleDateChange = (e) => {
        const { name, value } = e.target
        console.log(value)
        setTimeRange((prevDates) => ({
            ...prevDates,
            [name]: value
        }))
    }

    // 重置筛选
    const reset = () => {
        setTimeRange({ startDate: '', endDate: '' })
        setSelections({})
        setAddr([])
    }

    const handleButtonClick = () => {
        Toast.show({
            content: '正在导出~',
            icon: 'loading',
            duration: 0,
            maskClickable: false
        })
        let a = getSelected(selections)
        let params = {
            keyword,
            current: 1,
            size: 10,
            province: addr[0],
            city: addr[1],
            area: addr[2],
            street: addr[3],
            village: addr[4],
            checkTimeStart: timeRange.startDate ? `${timeRange.startDate} 00:00:00` : '',
            checkTimeEnd: timeRange.endDate ? `${timeRange.endDate} 23:59:59` : '',
            statusName: a['检查状态']?.join(),
            trade: a['行业类型']
        }
        try {
            exportWord(params).then(({ success, data, info }) => {
                Toast.clear()
                if (success && data) {
                    downloadFile(data)
                } else {
                    Toast.show({
                        icon: 'fail',
                        content: info
                    })
                }
            })
        } catch (err) {
            console.error('Error fetching file URL:', err)
        }
    }

    // 获取class名
    const getClassName = (text) => {
        const colorMap = {
            IN_RECTIFY: '#ffc107',
            NOT_RECTIFY: '#dc3545',
            PASS: '#28a745',
            HAVING_RECTIFY: '#28a745'
        }
        return colorMap[text] || ''
    }

    return (
        <div className="Shop">
            <div className="Shop_head">
                <div className="Shop_head_box">
                    <SearchBar onChange={setKeyword} onBlur={getData} value={keyword} placeholder="请输入店铺名称" />
                </div>
                <FilterOutline fontSize={25} onClick={() => setFilterVisible(true)} />
                <div className="Shop_head_title">
                    <p>
                        商户数量：{merchantNum} 检查记录数量：{recordNum}
                    </p>
                    <Button color="primary" size="mini" onClick={handleButtonClick}>
                        批量导出
                    </Button>
                </div>
            </div>
            <Popup position="top" visible={filterVisible} onMaskClick={closeTypeModal} onClose={closeTypeModal} bodyStyle={typeModalStyle}>
                <div className="filter_box">
                    <p className="filter_title">时间范围</p>
                    <div>
                        <input type="date" name="startDate" value={timeRange.startDate} onChange={handleDateChange} />
                        <span>&nbsp;&nbsp;-&nbsp;&nbsp;</span>
                        <input type="date" name="endDate" value={timeRange.endDate} onChange={handleDateChange} />
                    </div>
                    {categories.map((item) => (
                        <div key={item.title}>
                            <p className="filter_title">{item.title}</p>
                            <div className="filter_list">
                                {item.options.map((option) =>
                                    option ? (
                                        <p
                                            className={`${selections[item.title] && selections[item.title][option.option] ? 'active' : ''}`}
                                            key={option.option}
                                            onClick={() => handleSelect(item.title, option.option)}
                                        >
                                            {option.option}
                                        </p>
                                    ) : null
                                )}
                            </div>
                        </div>
                    ))}

                    <p className="filter_title">地址</p>
                    <div className="filter_list2">
                        <p>{addr.join('-')}</p>
                        <Button color="primary" size="mini" onClick={() => setVisible1(true)}>
                            选择地址
                        </Button>
                    </div>
                    <div className="type_btn">
                        <p onClick={reset}>重置</p>
                        <p onClick={closeTypeModal}>确认</p>
                    </div>
                </div>
            </Popup>
            {/* 三级联动 */}
            <Cascader
                options={addrData}
                visible={visible1}
                onClose={() => {
                    setVisible1(false)
                }}
                onConfirm={(e) => {
                    setAddr(e)
                }}
            />
            {/* 列表 */}
            <div className="Export_list">
                <Collapse>
                    {merchant?.records?.length
                        ? merchant?.records.map((item) => (
                              <Collapse.Panel
                                  key={item.id}
                                  title={
                                      <div style={{ display: 'flex', alignItems: 'center' }}>
                                          <Tag color="primary">{item.trade}</Tag>
                                          <p style={{ marginLeft: '10px', fontFamily: '黑体' }}>{item.unit}</p>
                                      </div>
                                  }
                              >
                                  <Button color="primary" size="mini" style={{ marginBottom: '10px' }} onClick={() => navigate(`/shop/${item.id}`)}>
                                      跳转该商户
                                  </Button>
                                  <Collapse>
                                      {item?.verifyList?.length
                                          ? item.verifyList.map((ee) => (
                                                <Collapse.Panel
                                                    key={ee.id}
                                                    title={
                                                        <>
                                                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                                                <p style={{ marginRight: '5px', fontSize: '14px', fontFamily: '黑体', color: '#000', fontWeight: '400' }}>{ee.checkTypeName}</p>
                                                                <Tag color={getClassName(ee.status)}>{ee.statusName}</Tag>
                                                            </div>
                                                            <p style={{ fontSize: '12px', fontFamily: '黑体', color: '#000', fontWeight: '400' }}>{ee.checkTime}</p>
                                                        </>
                                                    }
                                                >
                                                    <Space direction="vertical">
                                                        <p className="ShopDetails_list_p">
                                                            时间：<span>{ee.checkTime}</span>
                                                        </p>
                                                        <p className="ShopDetails_list_p">
                                                            单位：<span>{item.unit}</span>
                                                        </p>
                                                        <p className="ShopDetails_list_p">
                                                            负责人姓名：<span>{item.headName}</span>
                                                        </p>
                                                        <p className="ShopDetails_list_p">
                                                            电话：<span>{item.headPhone}</span>
                                                        </p>
                                                        <p className="ShopDetails_list_p">
                                                            单位地址：
                                                            <span>
                                                                {item.province}
                                                                {item.city}
                                                                {item.area}
                                                                {item.village}
                                                                {item.street}
                                                                {item.address}
                                                            </span>
                                                        </p>
                                                        <p className="ShopDetails_list_p">
                                                            行业类型：<span>{item.trade}</span>
                                                        </p>
                                                        <p className="ShopDetails_list_p">
                                                            检查类型：<span>{ee.checkTypeName}</span>
                                                        </p>
                                                        <div className="ShopDetails_list_p">
                                                            <p>检查人员（签名）：</p>
                                                            <Image src={ee.inspectorsSign} fit="contain" width={120} height={40} />
                                                        </div>
                                                        <div className="ShopDetails_list_p">
                                                            <p>被检查单位负责人（签名）：</p>
                                                            <Image src={ee.inspectedSign} fit="contain" width={120} height={40} />
                                                        </div>
                                                        <p className="ShopDetails_list_p">
                                                            限时整改时间：<span>{`${ee.rectifyDay}天` || '无'}</span>
                                                        </p>
                                                        <p className="ShopDetails_list_p">经查，存在以下问题：</p>
                                                        {ee?.records?.length ? (
                                                            ee.records.map((ee, ii) => (
                                                                <div key={ii}>
                                                                    <p className="ShopDetails_list_p" style={{ fontWeight: '400', marginBottom: '10px' }}>
                                                                        {ii + 1}.{ee.title}
                                                                    </p>
                                                                    <Space wrap>
                                                                        {ee.imageList.map((e, i) => (
                                                                            <Image src={e} width={100} height={100} fit="cover" key={i} />
                                                                        ))}
                                                                    </Space>
                                                                </div>
                                                            ))
                                                        ) : (
                                                            <p className="ShopDetails_list_p">无</p>
                                                        )}
                                                    </Space>
                                                </Collapse.Panel>
                                            ))
                                          : null}
                                  </Collapse>
                              </Collapse.Panel>
                          ))
                        : null}
                </Collapse>
            </div>
        </div>
    )
}

export default Shop
